package com.cpz.rabbitmq.message;

import lombok.Getter;
import lombok.ToString;
import org.springframework.amqp.core.Message;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @author cpz
 * @since 2022/09/19
 */
@Getter
@ToString
public abstract class RabbitMessage<T> implements Serializable {

    /**
     * 消息内容
     */
    private T data;
    public RabbitMessage<T> setData(T data) {
        this.data = data;
        return this;
    }

    /**
     * 消息唯一编号
     */
    private String messageId = UUID.randomUUID().toString();

    /**
     * 消息创建时间
     */
    private String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

    /**
     * 交换机
     * @return
     */
    public abstract String exchange();

    /**
     * 路由键
     * @return
     */
    public abstract String routingKey();

    /**
     * 将Message转换为消息基类
     * @param message
     * @return
     */
    public static RabbitMessage readObject(Message message) {
        byte[] body = message.getBody();
        ObjectInputStream ois = null;
        RabbitMessage rabbitMessage = null;
        try {
            ois = new ObjectInputStream(new ByteArrayInputStream(body));
            rabbitMessage = (RabbitMessage) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != ois) {
                    ois.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return rabbitMessage;
    }
}
